const template = require('art-template')
const path = require('path')
const url = require('url')
const queryString = require('querystring')

const {
  getData,
  getPage,
  writeData,
  addInfo
} = require('../common/utils')

// 获取首页
async function getIndex(req, res) {
  let data = await getData()
  // 获取数据和模版进行拼接
  let str = template(path.join(__dirname, '../pages/index.html'), data)
  res.end(str)
}

// 读取文件
async function sendPage(name, res) {
  await getPage(name, res)
}

// 删除功能
async function delData(req, res) {
  const id = url.parse(req.url, true).query.id
  // 取数据
  let data = await getData()
  // 删数据
  data.list.splice(data.list.findIndex(v => v.id == id), 1)
  // 写入数据
  await writeData(data)
  // 页面重定向到首页
  res.writeHead(302, {
    location: '/index'
  }).end()
}

// get添加功能
function subGet(req, res) {
  let info = url.parse(req.url, true).query
  addInfo(info, getData, writeData, res)
}

// post添加功能
async function subPost(req, res) {
  // 获取查询参数
  let params = ''
  await req.on('data', chunk => params += chunk)
  let info = queryString.parse(params)
  req.on('end', () => addInfo(info, getData, writeData, res))
}

// 404
function get404(req, res) {
  res.end('404')
}

// 导出
module.exports = {
  getIndex,
  sendPage,
  delData,
  subPost,
  subGet,
  get404
}